package com.monster.starter.core.filter;

import com.monster.common.Constant;
import com.monster.exception.impl.MonsterNoTackException;
import com.monster.starter.core.common.MonsterExceptionEnum;
import com.monster.starter.core.common.config.http.HttpRequestConfig;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 请求时间超时拦截器
 *
 * @author kuangxz
 */
@Slf4j
@Component
@Order(Constant.FILTER_TIME_OUT_ORDER)
public class RequestTimeOutFilter extends OncePerRequestFilter {
    /**
     * 配置
     */
    @Autowired
    private HttpRequestConfig config;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (config.getTimeGap() != 0) {
            // 获取请求头里面的时间
            String timeOut = request.getHeader(config.getTimeName());
            if (null == timeOut) {
                throw new MonsterNoTackException(MonsterExceptionEnum.TIME_GAP_ERROR, "没有获取到客户端时间,无法判定请求与服务器时间间隔");
            }
            Long timeOutInt = Long.parseLong(timeOut);
            Long systemTime = System.currentTimeMillis();
            if ((systemTime - timeOutInt) > config.getTimeGap()) {
                throw new MonsterNoTackException(MonsterExceptionEnum.TIME_GAP_ERROR, String.format("客户端时间：{},服务器时间：{},时间间隔太长，拦截请求", timeOutInt, systemTime));
            }
        }
        filterChain.doFilter(request, response);
    }
}
